//
//  AppDelegate.swift
//  sinaWeiBo
//
//  Created by smartlei on 15/10/14.
//  Copyright © 2015年 smartlei. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //1 创建window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        
        //2 设置为主window
        window?.makeKeyAndVisible()
        //3 创建控制器
        //window?.rootViewController = NewFeatureViewController()
        window?.rootViewController = defaultSetupRootViewController()
        //设置UITabBar的全局视图颜色
        setApperance()
        
         //接受消息中心发出的切换控制器消息
    NSNotificationCenter.defaultCenter().addObserverForName("WBNSNotificationCenterChangeViewController",//接受的消息名称
        object: nil,//接受任何对象发出的消息
        queue: nil)//为nil主队列
        { (notification) -> Void in
        //
            let vc = notification.object != nil ? WelcomeViewController() :MainViewController()
        self.window?.rootViewController = vc
        }
        return true
    }
    
    /// MARK - 设置渲染颜色
    private func setApperance() {
        
        UITabBar.appearance().tintColor = WBAppearanceColor
        UINavigationBar.appearance().tintColor = WBAppearanceColor
    }
    
    deinit{
        //从消息中心移除该条消息的通知
        NSNotificationCenter.defaultCenter().removeObserver(self, name: WBNSNotificationCenterChangeViewController, object: nil)
    }
    


}
extension AppDelegate {
   
    //设置默认启动控制器视图：根据
    private func defaultSetupRootViewController() -> UIViewController {
        //1 判断用户账号能否使用
        if UserAccountViewModel.sharedUserAccountViewModel.userLogon {
            //说明能够使用
            //再看是否是新版本，新本版显示新特性，旧版本则直接欢迎
            return isNewVersion ? NewFeatureViewController() :WelcomeViewController()
        }
        
        return MainViewController()
        
    }
    
    //判断是否是新版本
    private var isNewVersion: Bool  {
        //1 先从plist中获取当前版本
        let  currentVision = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let vision = Double(currentVision)
        
        //2 从偏好是设置中获取历史版本
        let  oldVision = NSUserDefaults.standardUserDefaults().doubleForKey("CFBundleShortVersionString")
        
        //3 保存新版本
        NSUserDefaults.standardUserDefaults().setDouble(vision!, forKey: "CFBundleShortVersionString")
        
        
        return vision > oldVision
        
        
        
    }
}

